package online.xybh.qa.controller;

import com.github.pagehelper.PageInfo;
import online.xybh.qa.anno.TeacherLogin;
import online.xybh.qa.dto.TeacherAndClassDTO;
import online.xybh.qa.model.Teacher;
import online.xybh.qa.service.StudentService;
import online.xybh.qa.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 17:29 2020/10/21
 * @Modified:
 */
@Controller
public class AdminController {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;
    @GetMapping("/admin")
    @TeacherLogin
    public String index(HttpSession session,
                        Model model){
        model.addAttribute("backUrl", "/admin");
        TeacherAndClassDTO user = (TeacherAndClassDTO)session.getAttribute("user");
        Teacher teacher = teacherService.queryTeacherById(user.getTeacherId());
        model.addAttribute("teacher", teacher);
        model.addAttribute("user", user);
        return "admin";
    }

    @RequestMapping("/admin/student")
    @TeacherLogin
    public String queryStudent(@RequestParam(value = "classId",defaultValue = "all") String classId,
                               @RequestParam(value = "page",defaultValue = "1") Integer page,
                               @RequestParam(value = "size",defaultValue = "10") Integer size,
                               HttpSession session,
                               Model model){
        PageInfo students;
        if (classId.equals("all")){
            students = studentService.queryAllStudent(page, size);
        }else{
            students = studentService.queryStudentByClassId(classId, page, size);
        }
        model.addAttribute("students", students);
        model.addAttribute("backUrl", "/admin/student?classId="+classId);
        TeacherAndClassDTO user = (TeacherAndClassDTO)session.getAttribute("user");
        model.addAttribute("user", user);
        return "admin_student";
    }

    @PostMapping("addStudent")
    @ResponseBody
    public Map<String,Object> addStudent(@RequestParam("stuId") String stuId,
                                         @RequestParam("stuName") String stuName,
                                         @RequestParam("stuClassId") String stuClass){
        studentService.addStudent(stuId, stuName, stuClass);
        HashMap<String, Object> res = new HashMap<>();
        res.put("code", 200);
        return res;
    }
}
